﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NETL.Data.Config;
using System.Reflection;
using log4net;

namespace NETL.Engine.Context
{
	public class ClassFactory
	{
		private static ClassFactory myInstance = new ClassFactory();
		private IDictionary<string, Assembly> myAssemblies = new Dictionary<string, Assembly>();
		private ILog myLogger = LogManager.GetLogger(typeof(ClassFactory));

		private ClassFactory()
		{
		}

		public static ClassFactory Instance()
		{
			return myInstance;
		}

		public object BuildClass(Class data)
		{
			Assembly asm = GetAssembly(data);

			Type t = asm.GetType(data.ClassName);

			return t.TypeInitializer.Invoke(new object[0]);
		}

		private Assembly GetAssembly(Class data)
		{
			Assembly asm;

			if (myAssemblies.ContainsKey(data.Assembly))
			{
				asm = myAssemblies[data.Assembly];
			}
			else
			{
				if (myLogger.IsDebugEnabled)
				{
					myLogger.DebugFormat("Loading assemby '{0}'", data.Assembly);
				}
				asm = Assembly.LoadFrom(data.Assembly);
			}

			return asm;
		}
	}
}
